#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include <unistd.h>
Log log;
void Usage(const std::string &proc)
{
    std::cout << "\n\rUsage: " << proc << " server_ip server_port\n" << std::endl;
}
// ./udp_client server_ip server_port
int main(int argc, char *argv[])
{   
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    socklen_t slen = sizeof(server);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        log(Fatal, "socket create err, errno: %d, err string: %s", errno, strerror(errno));
        exit(1);
    }
    log(Info, "socket create success");

    std::string message;
    char buffer[1024];
    while (true)
    {
        std::cout << "Please Enter@ ";
        std::getline(std::cin, message);
        // 1. 数据  2. 给谁发
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server, slen);

        struct sockaddr_in temp;
        socklen_t tlen = sizeof(temp);

        ssize_t s = recvfrom(sockfd, buffer, 1023, 0, (struct sockaddr*)&temp, &tlen);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << buffer << std::endl;
        }
    }
    close(sockfd);
    return 0;
}